package servlet;

import com.alibaba.fastjson.JSON;
import entity.User;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import service.UserService;
import service.imp.UserServiceImpl;
import utils.JSONUtil;
import utils.JdbcUtilsV1;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    UserService userService = new UserServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");



        // 调用service
        User user =  userService.login(username,password);
//        JSONUtil.printByJSON(resp,user);
//        resp.setContentType("text/json;charset=utf-8");
//        PrintWriter writer = resp.getWriter();
//        String s = JSON.toJSONString(user);
//        writer.print(s);
//        writer.flush();
//        writer.close();


        if (user != null) {

            // 登录成功
            req.getSession().setAttribute("user", user);
            // 跳转主页 转发
            req.getRequestDispatcher("index.jsp").forward(req, resp);
        }else{
            // 登录失败，账号密码不正确
            req.getRequestDispatcher("login.jsp").forward(req, resp);
        }
        // 接收请求  获取参数  业务逻辑  操作数据库

    }
}
